import {useRef, useState} from "react";
import {createPlainEvent} from "./event";
import type {ComponentEvent, ObjectEmitOptions} from "./emit.type";
import type {SimpleFunction} from "./event.type";

/**
 * 创建setupEvent对象
 * @author  韦胜健
 * @date    2021/3/9 18:14
 */
export function useEvent<T extends ObjectEmitOptions = {}>(fcProps: any, emitsOptions?: T): { setupEvent: ComponentEvent<T> } {
    const emitter = useRef({} as any)
    if (!!emitsOptions) {
        Object.keys(emitsOptions)
            .forEach(emitName => {
                emitter.current[emitName] !== fcProps[emitName] && (emitter.current[emitName] = fcProps[emitName])
                if (emitName === 'onUpdateModelValue' && emitter.current.onChange !== fcProps.onChange) {
                    emitter.current.onChange = fcProps.onChange
                }
            })
    }
    const [ret] = useState(() => {
        const event = createPlainEvent()

        const emit = {} as any;
        const on = {} as any;
        const once = {} as any;
        const off = {} as any;

        if (!!emitsOptions) {
            const keys = Object.keys(emitsOptions)
            if (emitsOptions.onUpdateModelValue) {keys.push('onChange')}

            keys.forEach(key => {
                emit[key] = (...args: any[]) => {
                    !!emitter.current[key] && emitter.current[key](...args)
                    event.emit(key, ...args)
                    if (key === 'onUpdateModelValue') {
                        !!emitter.current.onChange && emitter.current.onChange(...args)
                        event.emit('onChange', ...args)
                    }
                }
                on[key] = (fn: SimpleFunction) => event.on(key, fn)
                once[key] = (fn: SimpleFunction) => event.once(key, fn)
                off[key] = (fn: SimpleFunction) => event.off(key, fn)
            })
        }

        return {emit, on, once, off}
    })
    return {setupEvent: ret}
}
